/*
 * Copyright (c) 2018. QDU 2015 Java1 Team CompilationError
 */

package team.mai.antexpress.services;

import com.sun.istack.internal.Nullable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import team.mai.antexpress.dao.PermissionGroupDAO;
import team.mai.antexpress.dao.UserDAO;
import team.mai.antexpress.entities.PermissionGroupEntity;

import java.util.ArrayList;
import java.util.List;

@Service
public class PermissionGroupService {

	public static final int INTERNAL_ERROR = -2;
	public static final int INSUFFICIENT_PRIVILEGE = -1;


	@Autowired
	PermissionGroupDAO permissionGroupDAO;
	@Autowired
	UserDAO userDAO;

	@Nullable
	public List<PermissionGroupEntity> getPermissionGroups(String operatorUsername) {
		PermissionGroupEntity operatorPerm = userDAO.getPermissionByUser(operatorUsername);
		if (operatorPerm == null)
			return null;
		if (operatorPerm.isAdmin()) {
			return permissionGroupDAO.getAllPermissionGroups();
		} else {
			return null;
		}
	}

	@Nullable
	public PermissionGroupEntity getPermissionGroup(String operatorUsername, int groupId){
		PermissionGroupEntity operatorPerm = userDAO.getPermissionByUser(operatorUsername);
		if (operatorPerm.isAdmin()) {
			return permissionGroupDAO.getPermissionGroupById(groupId);
		} else {
			return null;
		}
	}

	public int insertPermissionGroup(String operatorUsername, PermissionGroupEntity group) {
		PermissionGroupEntity operatorPerm = userDAO.getPermissionByUser(operatorUsername);
		if (operatorPerm.isAdmin()) {
			return permissionGroupDAO.insertPermissionGroup(group);
		} else {
			return INSUFFICIENT_PRIVILEGE;
		}
	}

	public boolean deletePermissionGroups(String operatorUsername, List<Integer> groupIds) {
		PermissionGroupEntity operatorPerm = userDAO.getPermissionByUser(operatorUsername);
		if (operatorPerm.isAdmin()) {
			ArrayList<Integer> list = new ArrayList<>(groupIds);
			return permissionGroupDAO.deletePermissionGroupsById(list);
		} else {
			return false;
		}
	}

	public boolean updatePermissionGroup(String operatorUsername, PermissionGroupEntity group) {
		PermissionGroupEntity operatorPerm = userDAO.getPermissionByUser(operatorUsername);
		if (operatorPerm.isAdmin()) {
			return permissionGroupDAO.updatePermissionGroup(group);
		} else {
			return false;
		}
	}

}
